package androidvn.xenforo.fourums.widget;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.util.Log;

public class JsonParser {

	private static InputStream is = null;
	private static JSONObject jObj = null;
	static String json = null;

	public JsonParser() {

	}

	// function get json from url by making http post or get method
	public JSONObject makeHttpRequest(String url, String method,
			List<NameValuePair> params) {

		// make http request
		try {
			// check for request
			if (method == "POST") {

				// request method is POST
				// defaultHttpClient
				DefaultHttpClient client = new DefaultHttpClient();
				HttpPost post = new HttpPost(url);
				post.setEntity(new UrlEncodedFormEntity(params));
				// httpResponse
				HttpResponse response = client.execute(post);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();

			} else if (method == "GET") {

				// request method is GET
				DefaultHttpClient client = new DefaultHttpClient();

				// convert param to utf 8 then add to url
				String paramString = URLEncodedUtils.format(params, "utf-8");
				url += "&" + paramString;

				HttpGet get = new HttpGet(url);
				// httpResponse
				HttpResponse response = client.execute(get);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();

			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);

			StringBuilder sb = new StringBuilder();
			String line = null;

			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			jObj = new JSONObject(json);
		} catch (Exception e) {
			Log.e("JSONParser", "Error parsing data: " + e.toString());
		}
		return jObj;
	}
}
